import useStore from '@/store';
import { Directive, DirectiveBinding } from 'vue';

/**
 * 按钮权限校验
 */
export const hasPerm: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { user } = useStore();
    const perms = user.perms;
    // 拥有所有的权限
    if (perms.includes('*/**') || perms.includes('**/web/**')) {
      return true;
    }
    // 权限校验
    const { value } = binding;
    if (value) {
      const requiredPerms = value; // DOM绑定需要的按钮权限标识
      const hasPerm = perms.some((perm) => {
        if (perm.includes('get/**')) {
            //  正则匹配
            return  /^get\//.test(requiredPerms);
        }
        return requiredPerms.includes(perm);
      });
      if (!hasPerm) {
        el.parentNode && el.parentNode.removeChild(el);
      }
    } else {
      throw new Error(
        "need perms! Like v-has-perm=\"['sys:user:add','sys:user:edit']\""
      );
    }
  },
};


